use image::codecs::png::{CompressionType, FilterType, PngEncoder};
use image::Luma;
use qrcode::{EcLevel, QrCode};
use wasm_bindgen::prelude::*;
pub type StdErr = Box<dyn std::error::Error>;

#[wasm_bindgen]
pub fn generate_qr_code(text: &str) -> Result<Vec<u8>, JsValue> {
    // pub fn generate_qr_code(text: &str) -> Result<Vec<u8>, JsValue> {
    let qr = QrCode::with_error_correction_level(text, EcLevel::L);
    if let Ok(qr) = qr {
        let img_buf: image::ImageBuffer<Luma<u8>, Vec<u8>> = qr.render::<Luma<u8>>().min_dimensions(400, 400).build();

        let mut encoded_buf: Vec<u8> = Vec::with_capacity(512);
        let encoder: PngEncoder<&mut Vec<u8>> = PngEncoder::new_with_quality(
            &mut encoded_buf,
            CompressionType::Default,
            FilterType::NoFilter,
        );
        // img_buf.write_with_encoder(encoder).expect("msg");
        match img_buf.write_with_encoder(encoder){
            Ok(_) => println!("Image written successfully"),
            Err(e) => eprintln!("Failed to write image: {}", e),
        };
        return Ok(encoded_buf);
    } else {
        return Err(JsValue::from_str(&format!(
            "Error generating QR code: {:?}",
            "失败"
        )));
    }

    // return  text.to_string();
}
